package com.lyf.task.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.lyf.task.domain.Product;
import com.lyf.task.domain.Trade;
import com.lyf.task.domain.User;
import com.lyf.task.result.rfidResult;
import com.lyf.task.service.ProductService;
import com.lyf.task.service.RFIDUtilService;
import com.lyf.task.service.TradeService;
import com.lyf.task.service.UserService;
import com.lyf.task.util.DateFormatUtil;

@Controller
public class TradeController {

	@Autowired
	private TradeService tradeServiceImpl;

	@Autowired
	private ProductService productServiceImpl;

	@Autowired
	private UserService userServiceImpl;

	@Autowired
	private RFIDUtilService rfidUtilServiceImpl;

	@RequestMapping(value = "tradeByPid.html")
	public String tradeByPid(Model model, Integer pid) {

		List<Trade> list = tradeServiceImpl.getAllTradeByPid(pid);
		String pname = list.get(0).getProduct().getPname();

		model.addAttribute("pname", pname);
		model.addAttribute("tradeList", list);
		return "tradeRecordByPid";

	}

	@RequestMapping(value = "trade.html")
	public String getAllTrade(Model model) {

		model.addAttribute("tradeList", tradeServiceImpl.getAllTrade());
		return "trade";

	}

	@RequestMapping(value = "buy.html", method = RequestMethod.GET)
	public String buy(Model model, HttpSession httpSession, String pid, String price) {

		// ��Ӷ�����Ϣ
		User user = (User) httpSession.getAttribute("user");
		Trade trade = new Trade(Integer.parseInt(pid), user.getUid(), Double.parseDouble(price), new Date());
		tradeServiceImpl.insertTrade(trade);
		// �޸�product������Ϣ
		Product p = productServiceImpl.getOneProduct(pid);
		p.setLastTradeTime(new Date());
		p.setPrice(Double.parseDouble(price));
		p.setUserName(userServiceImpl.getUserByUserName(user).getRealName());
		p.setTradeTimes(p.getTradeTimes() + 1);
		productServiceImpl.updateProduct(p);

		// ���rfid����

		rfidResult rs = new rfidResult();
		rs.setPid(p.getPid());
		rs.setDegree(p.getDegree());
		rs.setTradeTime(p.getTradeTimes());
		rs.setDate(DateFormatUtil.dateformat(new Date()));
		rfidUtilServiceImpl.writeNewRfid(rs);
		return "success";

	}
}
